using System;
using System.Collections;
using SCore.Util;
using UnityEngine;
using UnityEngine.Networking;

namespace Function.HotUpdate
{
    [Serializable]
    public class Lighthouse
    {
        #region data

        public string lighthouse_id;
        public ResDetial res_detail; //当前资源版本号
        public string url_store; //商店地址

        // public Maintenance maintenance;
        // public bool maintenance_open; //是否在维护。有两种情况生效：1 跟游戏服务器确认以后 2 连接不上游戏服务器
        // public string url_pattern; //维护信息
        public Server[] servers;

        //public ErrorResponse errorResponse;

        #endregion // data

        #region method

        public string GetRemoteResVersion(string injectEnv)
        {
            if (string.IsNullOrEmpty(injectEnv))
            {
                return res_detail.res_version;
            }
            else
            {
                UnityEngine.Debug.Log(
                    $"[hotupdate] use inject res version {res_detail.inject_res_version}");
                return res_detail.inject_res_version;
            }
        }

        public static Lighthouse CreateFromJson(string json)
        {
            return JsonUtility.FromJson<Lighthouse>(json);
        }

        // Action<Lighthouse, string>, string -> error
        public static IEnumerator NewFromUrl(string url, Action<Lighthouse, string> callback)
        {
            var request = UnityUtils.GetUnityWebRequestNoSafe(url);
            request.timeout = 15;
            request.disposeDownloadHandlerOnDispose = true;
            request.downloadHandler = new DownloadHandlerBuffer();
            yield return request.SendWebRequest();
            if (request.result == UnityWebRequest.Result.ProtocolError || request.error != null)
            {
                callback(null, request.error);
                request.Dispose();
                yield break;
            }

            var data = request.downloadHandler.data;
            request.Dispose();
            // yy 统一使用无bom头格式
            string jsonString = System.Text.Encoding.UTF8.GetString(data);
            UnityEngine.Debug.Log($"LightHouse str: {jsonString}");

            var lighthouse = CreateFromJson(jsonString);
            callback(lighthouse, null);
            yield break;
        }

        #endregion // method
    }

    [Serializable]
    public class Server
    {
        public string name;
        public Maintenance maintenance;

        public string url; //服务器的url - default

        // public string url_asia; // 亚洲服务器的url
        public string version_min; //支持的最小版本号（包含）
        public string version_max; //支持的最大版本号（不包含）
        public string[] fallback; //服务器的备用地址 - 意义不大了
    }

    // [Serializable]
    // public class UpdateInfo
    // {
    //     public string version;
    //     public string url_package;
    //     public string url_store;
    //     public string url_desc;
    //     public string title_desc;
    //     public int display_per_day;
    // }

    // [Serializable]
    // public class VersionRequest
    // {
    //     public string lighthouse_id;
    //     public string from;
    //     public string app_version;
    //     public string platform;
    // }

    // [Serializable]
    // public class ErrorResponse
    // {
    //     public int code;
    //     public string message;
    // }

    [Serializable]
    public class Maintenance
    {
        public bool open;
        public string url;
        public string notice_url;
    }

    // [Serializable]
    // public class AppUpdateInfo
    // {
    //     public string version;
    //     public string url_package;
    //     public string url_store;
    //     public string url_desc;
    //     public string title_desc;
    //     public int display_per_day;
    // }

    [Serializable]
    public class ResDetial
    {
        // 不应该直接使用，，请使用：HotContext.GetRemoteResVersion
        public string res_version;

        // 但凡有注入，统一用这个
        public string inject_res_version;
    }
}